function bindClick() {
  $('#get_email_captcha').click(function(event) {
    var btn = $(this);
    event.preventDefault();
    var em = $('#reg-email').val();
    // alert(em)
    if (!em) {
      layer.msg('请输入邮箱');
    } else {
      fetch(`/captcha/email?email=${em}`, {
        method: 'GET',
      }).then(function(response) {
        return response.json();
      }).then(function(ret) {
        if (!ret.code) {
          layer.msg(ret.message, {icon: 1});
          var countdown = 5;
          btn.off('click');
          var timmer = setInterval(function() {
            btn.text(countdown + 's');
            countdown -= 1;
            if (countdown <= 0) {
              // 寝宫定时器
              clearInterval(timmer);
              btn.text('获取验证码');
              bindClick();
            }
          }, 1000);
        }
      });
    }
  });
}

$(function() {
  bindClick();
});

layui.use(
    function() {
      var $ = layui.$;
      var form = layui.form;
      var layer = layui.layer;
      var util = layui.util;
      form.on('submit(demo-reg)', function(data) {
        var field = data.field; // 获取表单字段值
        // alert(field);
        console.log(field);
        // 是否勾选同意
        if (!field.agreement) {
          layer.msg('您必须勾选同意用户协议才能注册');
          return false;
        }

        // 此处可执行请求操作
        fetch('/register', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(field),
        }).then(response => response.json()).then(res => {
          // 处理后端的响应数据
          if (!res.code) {
            layer.msg(res.message, function() {
              setTimeout(function() {
                location.href = '/login';
              }, 2000); // 2秒后跳转
            });
          } else {
            // 错误信息
            layer.msg(res.message, {icon: 2});
          }
        });

        return false; // 阻止默认 form 跳转
      });
    },
);

